package main.Web;

import com.alibaba.fastjson.JSON;
import main.Service.FriendshipService;
import main.Service.UserService;
import main.ServiceImpli.FriendshipServiceImpl;
import main.ServiceImpli.UserServiceImpl;
import main.pojo.Friendship;
import main.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: ALIM-MASTIK
 * 创建实现: 2023/7/14 11:59
 * 项目名称：chat
 * 软件: IntelliJ IDEA
 */
@WebServlet("/Index")
public class Index extends HttpServlet {
    UserService userService=new UserServiceImpl();
    FriendshipService friendshipService=new FriendshipServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Map<String,Object> map=new HashMap<>();
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        User user1=new User();
        System.out.println(username);
        user1.setUsername(username);
        user1.setPassword(password);
        if (userService.CheckLogin(user1)){
            List<User> Friend=new ArrayList<>();
            map.put("checklogin",true);
            System.out.println("登陆成功");
            user1=userService.getUserByUserNameAndPassword(username,password);
            req.getSession().setAttribute("user",user1);
            for (Friendship friendship:friendshipService.getFriendshipsByUser(user1.getUserID())){
                User user=userService.getUserByID(friendship.getFriendID());
//                System.out.println(user.toString());
                Friend.add(user);
            }
            req.getSession().setAttribute("Friends",Friend);
        }else {
            map.put("checklogin",false);
        }
        User user = userService.getUserByUsername(username);
        if (user!=null){
            map.put("checkuser",true);
        }else {
            map.put("checkuser",false);
            System.out.println("不要轻举妄动，这个对象是空的");
        }
        String json = JSON.toJSONString(map);
        PrintWriter pw = resp.getWriter();
        pw.print(json);
    }
}
